package com.zhu.config;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 设置请求和连接超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(1000)  // 连接超时时间 (ms)
                .setConnectionRequestTimeout(1000) // 请求队列超时时间 (ms)
                .setSocketTimeout(5000) // 数据读取超时时间 (ms)
                .build();
        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        // 创建 HttpClient 请求工厂
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

        // 创建 RestTemplate
        return new RestTemplate(requestFactory);
    }
}

